import './App.css'
import React from 'react'
import { BrowserRouter, useRoutes } from 'react-router-dom'
import routes from '~react-pages'

const App = () => {
    // 路由列表
    const Routes = () => {
        React.navigate = useNavigate()

        // 获取当前访问路由的地址
        const { pathname } = useLocation()

        // 全局参数接收
        let [searchParams] = useSearchParams()

        React.params = (name: string) => searchParams.get(name ?? '')

        // 需要登录的路由判断
        if(!React.RouterRules.includes(pathname)) CheckLogin()
        
        return useRoutes(routes)
    }

    // 登录判断（路由守卫）
    const CheckLogin = async () => {
        let id = React.business.id ?? 0
        let mobile = React.business.mobile ?? ''

        let result = await React.request.post('/business/UserCheck', {id, mobile})

        if(result.code == 0)
        {
            // 移除cookie
            React.cookies.remove('business', {path: '/'})
            React.business = {}

            // 跳转到登录界面
            React.toast(result.msg, 'fail', result.url)
            return false
        }

        // 覆盖cookie信息
        React.business = result.data
        React.cookies.save('business', result.data, {path: '/'})
        return false
    }

    //页面加载中loading...
    const fallback = () => (<React.UI.AutoCenter><React.UI.DotLoading color='primary' /></React.UI.AutoCenter>)

    return (
        <BrowserRouter>
            <React.Suspense fallback={fallback()}>
                <Routes />
            </React.Suspense>
        </BrowserRouter>
    )
}

export default App
